<template>
  <view class="pagebox">
    <!-- Header -->
    <view class="pond-head" @tap="init">
      <image :src="pondHeadImg" alt="pond head"></image>
    </view>

    <!-- Prize Container -->
    <view class="container-out">
      <view class="container-in">
        <!-- Prize Items -->
        <view
          class="content-out"
          v-for="(box, index) in state.list"
          :key="box.id"
          :style="{
            left: `${box.left}px`,
            top: `${box.top}px`,
            backgroundColor: index === state.indexSelect ? state.colorAwardSelect : state.colorAwardDefault,
          }"
        >
          <image class="pond-name-img" :src="box.image_url" alt="prize"></image>
          <view class="pond-name">{{ box.name }}</view>
        </view>
      </view>

      <!-- Start Button -->
      <view class="start-btn" @tap="startGame">
        <image :src="pondCjImg" :style="{ top: `${state.btntop}px` }" class="cj-img" alt="start spinning" />
      </view>

      <!-- Circles -->
      <view
        class="circle"
        v-for="(circle, index) in state.circleList"
        :key="index"
        :style="{
          top: `${circle.topCircle}px`,
          left: `${circle.leftCircle}px`,
          backgroundColor: index % 2 === 0 ? state.colorCircleFirst : state.colorCircleSecond,
        }"
      ></view>
    </view>

    <!-- Prize Result -->
    <view v-if="state.prize" class="prize">
      <view class="prize-box">
        <image :src="prizeSuccessImg" alt="prize image"></image>
        <view class="prize-msg">
          <view>{{ `恭喜抽中 ${state.prizeName}` }}</view>
          <view class="continue" @tap="resetGame">好的</view>
        </view>
      </view>
    </view>

    <!-- Modal -->
    <view v-if="state.isModalVisible" class="modal-overlay"></view>
  </view>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";

// Static assets
const pondHeadImg =
  "https://www.xiaomicang.com/static/image/pond-head.png";
const pondButtonImg =
  "https://www.xiaomicang.com/static/image/pond-button.png";
const pondCjImg =
  "https://www.xiaomicang.com/static/image/pond-cj.png";
const prizeSuccessImg =
  "https://www.xiaomicang.com/static/image/pond-success.png";
const prizeEmptyImg =
  "https://www.xiaomicang.com/static/image/pond-empty.png";

// State management
const state = reactive({
  list: [],
  circleList: [],
  colorCircleFirst: "#F12416",
  colorCircleSecond: "#FFFFFF",
  colorAwardDefault: "#F5F0FC",
  colorAwardSelect: "#ffe400",
  btntop: 0,
  indexSelect: 0,
  selectedPrizeIndex: null,
  prize: 0,
  prizeName: "",
  isModalVisible: false,
  timer: null,
});

// Initialize layout and animations
const init = () => {
  // Layout prize boxes
  const setPrizePositions = () => {
    const positions = [
      { left: 9, top: 9 },
      { left: 111, top: 9 },
      { left: 213, top: 9 },
      { left: 213, top: 92 },
      { left: 213, top: 175 },
      { left: 111, top: 175 },
      { left: 9, top: 175 },
      { left: 9, top: 92 },
    ];

    state.list.forEach((item, index) => {
      if (positions[index]) {
        item.left = positions[index].left;
        item.top = positions[index].top;
      }
    });
  };

  // Generate decorative circles
  const generateCircles = () => {
    state.circleList = Array(24)
      .fill()
      .map((_, i) => ({
        topCircle: 4 + Math.floor(i / 6) * 46,
        leftCircle: 4 + (i % 6) * 55,
      }));
  };

  // Start circle animation
  const startCircleAnimation = () => {
    state.timer = setInterval(() => {
      [state.colorCircleFirst, state.colorCircleSecond] = [
        state.colorCircleSecond,
        state.colorCircleFirst,
      ];
    }, 900);
  };

  setPrizePositions();
  generateCircles();
  startCircleAnimation();
};

// Start game logic
const startGame = () => {
  clearInterval(state.timer); // Stop animations
  state.isModalVisible = true; // Show overlay

  // Check if there is a winner among the prizes
  const winner = state.list.find((box) => box.is_winner === 1);

  if (winner) {
    const totalSteps = 50 + Math.floor(Math.random() * 20); // Random spin duration
    let currentStep = 0;

    const interval = setInterval(() => {
      state.indexSelect = (state.indexSelect + 1) % state.list.length;

      if (++currentStep >= totalSteps) {
        clearInterval(interval);
        state.isModalVisible = false; // Hide overlay
        state.selectedPrizeIndex = state.indexSelect; // Update selected prize index
        state.prize = winner.type;
        state.prizeName = winner.name;
      }
    }, 100);
  }
};

// Reset game state
const resetGame = () => {
  state.isModalVisible = false;
  state.prize = 0;
  state.prizeName = "";
  state.indexSelect = 0;
};

onLoad(async () => {
  randomPrizes();
});

async function randomPrizes() {
  let res = {};

  res = await sheep.$api.app.randomPrizes();

  if (res.code === 1) {
    state.list = res.data;
    init();
  }
  // alert(JSON.stringify(state.list))
}
</script>
<style lang="scss" scoped>
	.pagebox {
		width: 100%;
		height: 100vh;
		background: #f12416;
	}

	.pond-head image {
		width: 100%;
		height: 430rpx;
	}

	.container-out {
		height: 283px;
		width: 340px;
		background-color: #F47915;
		margin: 16px auto 15px auto;
		border-radius: 8px;
		position: relative;
	}

	.circle {
		position: absolute;
		display: block;
		border-radius: 50%;
		height: 7px;
		width: 7px;
	}

	.content-out {
		position: absolute;
		height: 72px;
		width: 98px;
		background-color: #f5f0fc;
		border-radius: 8px;
		box-shadow: 0 8px 0 #FFCEC0;
	}

	.container-in {
		width: 320px;
		height: 263px;
		background-color: #f12416;
		border-radius: 10px;
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		margin: auto;
	}

	.pond-name-img {
		position: absolute;
		top: 6px;
		left: 0;
		width: 100%;
		height: 46px;
		z-index: 1;
	}

	.pond-name {
		position: absolute;
		top: 75%;
		color: #c62015;
		width: 98px;
		overflow: hidden;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		font-size: 9pt;
		text-align: center;
	}

	.start-btn {
		position: absolute;
		margin: auto;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		border-radius: 8px;
		height: 79px;
		width: 98px;
		color: #f6251e;
		text-align: center;
		font-weight: bolder;
		line-height: 77px;

		image {
			height: 79px;
			width: 98px;
		}

		.cj-img {
			height: 79px;
			width: 98px;
		}
	}

	.prize {
		background: rgba(0, 0, 0, 0.25);
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		z-index: 1;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		-ms-grid-row-align: center;
		align-items: center;
		z-index: 100;
	}

	.prize-box {
		margin: 0 auto;
		position: relative;
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.prize-img {
		width: 100vw;
		max-height: 231px;
		max-width: 375px;
	}

	.prize-img2 {
		width: 100vw;
		max-height: 120px;
		max-width: 375px;
	}

	.prize-msg {
		width: 78.5vw;
		max-width: 294.5px;
		text-align: center;
		background: #ffffff;
		padding-bottom: 6px;
		font-size: 13pt;
	}

	.prize_name {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.continue {
		width: 240px;
		height: 40px;
		margin: 28px auto;
		background: #ff5c5c;
		line-height: 40px;
		color: #ffffff;
		border-radius: 20px;
	}

	.men {
		position: fixed;
		width: 100vw;
		height: 100vh;
		z-index: 1;
		left: 0;
		top: 0;
	}
</style>